package worker;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.util.zip.GZIPInputStream;

public class ClassLoaderObjectInputStream extends ObjectInputStream {

	private RemoteClassLoader classLoader;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	int problemNumber;
	int version;

	// public ClassLoaderObjectInputStream(ClassSolver classSolver, int
	// problenNum, int version) throws IOException {
	// ClientInfo clientInfo = classSolver.getClientInfo(problenNum, version);
	// classLoader = new RemoteClassLoader(clientInfo.getOut(),
	// clientInfo.getIn());
	// // TODO Auto-generated constructor stub
	// }

	public ClassLoaderObjectInputStream(InputStream stream, int problemNumber, int version,
			ObjectInputStream in, ObjectOutputStream out) throws IOException {
		super(in);
		this.problemNumber = problemNumber;
		this.version = version;
		this.out = out;
		this.in = in;
		classLoader = new RemoteClassLoader(problemNumber, version, out, in);
	}

	public ClassLoaderObjectInputStream(InputStream stream, ObjectInputStream in,
			ObjectOutputStream out) throws IOException {
		super(stream);
		this.problemNumber = -1;
		this.version = -1;
		this.out = out;
		this.in = in;
		classLoader = new RemoteClassLoader(out, in);

	}



	@Override
	protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException,
	ClassNotFoundException {
		try {
			String name = desc.getName();
			System.out.println("Need " + name);
			return Class.forName(name, false, classLoader);
		} catch (ClassNotFoundException e) {
			return super.resolveClass(desc);
		}
	}

	public void setProblemAndVersion(int problemNumber, int version) {
		if(this.problemNumber!=problemNumber || this.version != version){
			this.problemNumber = problemNumber;
			this.version = version;
			classLoader = new RemoteClassLoader(problemNumber, version, out, in);
		}
	}
}